const { default: axios } = require("axios");
const alipaySdk = require("../../utils/alipay");
const response = require("../../utils/response");
const validate = require("../../utils/validate");
const { addOreerRules, deleteOrderRules, cancelOrderRules } = require("../validations/orderValidations");
const { getOrderListByPage, addOrder, deleteOrder, updateOrderStatus, getOrderById } = require("../services/orderService");
const { getUserById } = require("../services/userService");

class orderController {
    async addOrder(ctx){
        try {
            const totalAmount = 9;
            const outTradeNo = Date.now();

            // 填写订单基础信息
            const bizContent = {
                out_trade_no: outTradeNo,
                total_amount: totalAmount,
                subject: '付款',
            }

            const resultUrl = alipaySdk.pageExec('alipay.trade.precreate', {
                method: 'GET',
                bizContent,
                notify_url: "http://ckck.life:8888/notify"
            });

            let { data } = await axios.get(resultUrl);
            console.log(data, 'data')
            if(data.alipay_trade_precreate_response.code !== '10000') throw '获取支付二维码失败';
            
            await addOrder({
                orderId: outTradeNo,
                total: totalAmount,
                userId: ctx.state.user.id,
                paymentMethod: 'alipay'
            });

            response.success(ctx, {
                qrcode: data.alipay_trade_precreate_response.qr_code,
                orderId: outTradeNo
            });
        }catch(err){
            response.error(ctx, err);
            console.log(err, 'pay');
        }
    }
    async notify(ctx){
        try {
            const { out_trade_no, trade_status } = ctx.request.body;

            if(trade_status === 'TRADE_SUCCESS'){
                let orderInstance = await getOrderById(out_trade_no);
                orderInstance.setDataValue('paymentStatus', 'paid');
                await orderInstance.save();
                let userInstance = await getUserById(orderInstance.dataValues.userId);
                
                let time = userInstance.dataValues.membershipExpireAt ? new Date(userInstance.dataValues.membershipExpireAt).getTime() : Date.now()
                userInstance.setDataValue('membershipExpireAt', time + 31 * 24 * 60 *60 * 1000);
                await userInstance.save();
            }
            ctx.body = 'ok';
        }catch(err){
            response.error(ctx, err);
            console.log(err, 'pay');
        }
    }
    async getOrderStatus(ctx){
        try {
            const { id } = await validate(ctx, deleteOrderRules);
            const order = await getOrderById(id);
            if(!order) throw '没有找到对应记录'
            
            response.success(ctx, order);
        }catch(err){
            response.error(ctx, err);
            console.log(err, 'pay');
        }
    }
    async deleteOrder(ctx) {
        try {
            const { id } = await validate(ctx, deleteOrderRules);

            const affectedRows = await deleteOrder(id);
            if (affectedRows > 0) {
                response.success(ctx, id, '删除成功')
            } else {
                response.error(ctx, '删除失败')
            }
        } catch (err) {
            console.log(err)
            response.error(ctx, err);
        }
    }
    async getOrderListByPage(ctx) {
        const usp = new URLSearchParams(ctx.querystring);
        let page = Number(usp.get('page')) || 1;
        let limit = Number(usp.get('limit')) || 10;
        let keyword = usp.get('keyword') || '';
        let sort = usp.get('sort') || 'DESC';
        let paymentStatus = usp.get('paymentStatus') || '';
        try {
            const { rows, count } = await getOrderListByPage(page, limit, keyword, sort, paymentStatus);
            response.success(ctx, {
                page,
                limit,
                rows,
                total: count
            });
        } catch (err) {
            console.log(err, 'getOrderListByPage')
            response.error(ctx, err);
        }
    }
    // 取消订单
    async cancelOrder(ctx){
        try {
            const { id } = await validate(ctx, cancelOrderRules);
            const orderInstance = await getOrderById(id);
            if(!orderInstance) throw '未找到对应记录';

            orderInstance.setDataValue('paymentStatus', 'cancelled');
            await orderInstance.save();

            response.success(ctx, id)
        } catch (err) {
            console.log(err)
            response.error(ctx, err);
        }
    }
}

module.exports = new orderController();